<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>商品列表</title>
    <link href="../static/css/bootstrap.css" rel="stylesheet" type="text/css"/>
    <link href="../static/css/components.min.css" rel="stylesheet" type="text/css"/>
    <link href="../static/css/login.css" rel="stylesheet" type="text/css"/>
    <script src="../static/js/jquery-1.11.2.min.js" type="text/javascript"></script>
</head>
<body>
    <div class="content">
        <h3 class="form-title">商品列表</h3>
        <div class="table-response">
            <table class="table">
                <thead>
                    <tr>
                        <th>商品名</th>
                        <th>商品图片</th>
                        <th>商品描述</th>
                        <th>商品价格</th>
                        <th>商品库存</th>
                        <th>商品销量</th>
                    </tr>
                </thead>
                <tbody id="container">
    
                </tbody>
            </table>
        </div>
        
    </div>
</body>

<script>
    var itemList = [];
    // DOM加载完毕后再执行
    jQuery(document).ready(function(){

        $.ajax({
            type: "GET",
            url: "http://localhost:8888/items",
            xhrFields: {
                withCredentials: true
            },
            success: (res)=>{
                if (res.status == "success") {
                    itemList = res.data;
                    reloadDom();
                } else {
                    alert("获取失败，原因为：" + res.data.errorMessage);
                }
            },
            error: (res)=>{
                alert("获取错误，原因为：" + res.responseTesxt);
            }
        })
        
    });

    function reloadDom() {
        for (var i = 0; i < itemList.length; i++) {
            var itemVO = itemList[i];
            var dom = "<tr data-id='" + itemVO.id + "' id='itemDetail" + itemVO.id + "'><td>" + itemVO.title + "</td><td><img src='" + itemVO.imgUrl + "' style='width:100px;height:auto;'></td><td>" + itemVO.description + "</td><td>" + itemVO.price + "</td><td>" + itemVO.stock + "</td><td>" + itemVO.sales + "</td></tr>";
            $("#container").append(dom);

            $("#itemDetail" + itemVO.id).on("click",function(event){
                window.location.href="getItem.html?id=" + $(this).data("id");
            })
        }
    }
</script>

</html>